import React from 'react';
import { Modal } from 'antd';
import BasicInformation from './basicInformation';
import { connect } from 'dva';
import { encode } from '@/utils/AesUtil';

@connect(
  state => ({
    loadingupdate: state.loading.effects['database/update'],
  }),
  dispatch => ({
    update: e => dispatch({ type: 'database/update', payload: e }),
  })
)
export default class Edit extends React.Component {
  state = {
    modalVisible: false,
  };
  handleModalVisible = () => {
    if (this.props.disabled) return;
    this.setState(() => ({ modalVisible: !this.state.modalVisible }));
  };
  okHandle = () => {
    this.basicInformation.props.form.validateFields(async (err, values) => {
      if (err) return;
      this.props
        .update({
          dbId: this.props.text.dbId,
          ...values,
          dbPassword: values.dbPassword && (await encode(values.dbPassword)),
        })
        .then(res => {
          if (res.rescode == 200) {
            this.handleModalVisible();
            Modal.success({ title: '操作成功' });
            this.props.pageList();
          } else {
            Modal.error({ title: '操作失败', content: res.msg });
          }
        });
    });
  };
  render() {
    return (
      <>
        <Modal
          destroyOnClose
          width={640}
          title="编辑数据库"
          visible={this.state.modalVisible}
          onOk={this.okHandle}
          onCancel={this.handleModalVisible}
          maskClosable={false}
          confirmLoading={this.props.loadingupdate}
        >
          <BasicInformation
            {...this.props}
            getInstance={childCp => {
              this.basicInformation = childCp;
            }}
          />
        </Modal>
        <span onClick={this.handleModalVisible}>{this.props.children}</span>
      </>
    );
  }
}
